﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using JESAI.ClamAV.NetScanner.Demo.Models;
using System.IO;
using Microsoft.AspNetCore.Http;
using JESAI.ClamAV.NetScannerCore;
using JESAI.ClamAV.NetScannerCore.Models;
using Newtonsoft.Json;

namespace JESAI.ClamAV.NetScanner.Demo.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IClamAVScannerClient ClamAVScannerClient;
        public HomeController(ILogger<HomeController> logger, IClamAVScannerClient clamAVScannerClient)
        {
            _logger = logger;
            ClamAVScannerClient = clamAVScannerClient;
        }

        public async Task<IActionResult> Index()
        {
            var ver = await ClamAVScannerClient.GetVersionAsync();
            ViewBag.ServerInfo = $"服务器:{ver}";
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        [HttpPost]
        public async Task<IActionResult> Upload(List<IFormFile> files)
        {
            long size = files.Sum(f => f.Length);
            List<ScannerResult> list = new List<ScannerResult>();
            foreach (var formFile in files)
            {
                using var stream = formFile.OpenReadStream();
                var reault = await ClamAVScannerClient.SendAndScanFileAsync(stream);
                list.Add(reault);
            }
            TempData["list"] = JsonConvert.SerializeObject(list);
            return RedirectToAction("ScanResult");
        }
        public IActionResult ScanResult()
        {
            if (TempData["list"] == null)
            {
                return RedirectToAction("Index");
            }
            var list = JsonConvert.DeserializeObject<List<ScannerResult>>(TempData["list"].ToString());
            return View(list);
        }
    }
}
